package com.sense.kukoo.common.mvvm.view

import android.os.Build
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Toast
import androidx.databinding.DataBindingUtil
import androidx.databinding.ViewDataBinding
import androidx.fragment.app.Fragment
import androidx.lifecycle.LifecycleOwner
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModelProvider
import com.sense.kukoo.common.R
import com.sense.kukoo.common.mvvm.vm.BaseViewModel
import com.sense.kukoo.common.wiget.dialog.LoadDialog
import com.zy.multistatepage.MultiStateContainer
import com.zy.multistatepage.bindMultiState


/**
@Author Lionszhang
@Date   2021/2/25 16:36
@Name   BaseFragment.kt
@Instruction MVVM层Fragment基类，所有Fragment子界面应当继承
 */
abstract class BaseMvvmFragment<V : BaseViewModel, B : ViewDataBinding> : Fragment(), IView {

    lateinit var mBinding: B
    lateinit var mViewModel: V
    private var TAG: String? = "BaseFragment"
    protected var mSavedInstanceState: Bundle? = null
    private var loadingProgressDialog: LoadDialog? = null
    protected lateinit var multiState: MultiStateContainer

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        mSavedInstanceState = savedInstanceState
        initParam()
    }

    /**参数初始化*/
    abstract fun initParam()

    fun isViewModelInit(): Boolean{
        return ::mViewModel.isInitialized
    }

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        mBinding = DataBindingUtil.inflate(inflater, getLayout(), container, false)
        mViewModel = createViewModel(getViewModelClass())
        multiState = mBinding.root.bindMultiState()
        return multiState
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        addLiveDataObserve()
        initData()
        initView()
    }

    private var flag_to_init:Boolean = true

    override fun onResume() {
        super.onResume()
        if (flag_to_init) {
            flag_to_init = false
            singleLazyLoad()
        }
    }

    //只会执行一次的初始化
    open fun singleLazyLoad(){}

    /**
    @Author  Lionszhang
    @Date   2021/2/24 15:06
    @Return  返回Activity对应的ViewModel
     */
    protected open fun createViewModel(clazz: Class<V>): V {
        return ViewModelProvider(requireActivity()).get(clazz)
    }

    private fun addLiveDataObserve() {
        mViewModel.mHintInfoLiveData.observe(viewLifecycleOwner) {
            Toast.makeText(activity, it, Toast.LENGTH_SHORT).show()
        }

        /**VM层与V层交互默认处理方式*/
        mViewModel.mNavLiveDate.observe(viewLifecycleOwner) {
            when (it) {
                BaseViewModel.ACTION_SHOW_DIALOG -> {
                    getLoadingProgressDialog()?.show()
                }
                BaseViewModel.ACTION_HIDE_DIALOG -> {
                    hideLoadingDialog()
                }
                else -> {
                    responseVM(it)
                }
            }
        }

        mViewModel.mShowNetworkError.observe(viewLifecycleOwner){ networkError ->
            networkError?.let {
                mViewModel.mShowNetworkError.value = null
                onShowNetworkError()
            }
        }
    }

    /*
    * 默认的网络错误实现，默认为空，由子类实现
    * ToastUtils.showToast(getString(com.sense.kukoo.common_i18n.R.string.search_no_net_toast))
    *    multiState.show<NetworkErrorState> {
    *        it.onRetry {
    *            //mViewModel.retryNetwork()
    *        }
    *    }
    * */
    open fun onShowNetworkError(){}

    /**
     * 获取状态栏颜色
     */
    open fun getStatusBarColor(): Int {
        return R.color.colorPrimary
    }

    /**
    @Author  Lionszhang
    @Date   2021/3/8 16:09
    @Param action 动作常量
    @Instruction  对VM层的默认响应函数
     */
    abstract override fun responseVM(action: Int)


    abstract fun getLayout(): Int

    protected  fun showLoadingDialog() {

        if (activity!=null&&activity?.isFinishing != true){

            getLoadingProgressDialog()?.show()
        }
    }
    /**
     * 获取ViewModel的class
     */
    abstract fun getViewModelClass(): Class<V>

    private fun getLoadingProgressDialog(): LoadDialog? {
        if (activity!=null&&activity?.isFinishing != true) {
            if (loadingProgressDialog == null) {
                loadingProgressDialog = this.activity?.let { LoadDialog(it) }
            }
        }
        return loadingProgressDialog
    }

    protected fun hideLoadingDialog() {
        if (loadingProgressDialog?.isShowing==true) {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                loadingProgressDialog?.dismiss()
            } else {
                loadingProgressDialog?.hide()
            }
        }
    }

    protected fun <T> bindAction(data: MutableLiveData<T>, owner: LifecycleOwner, action:(t:T)->Unit){
        data.observe(owner){
            it?.let {
                data.value = null
                action(it)
            }
        }
    }

    protected fun <T> bindAction(data: MutableLiveData<T>, action:(t:T)->Unit){
        bindAction(data, viewLifecycleOwner, action)
    }

    protected fun <T> bindData(
        data: MutableLiveData<T>,
        owner: LifecycleOwner,
        action: (t: T) -> Unit
    ) {
        data.observe(owner, action)
    }

    protected fun <T> bindData(data: MutableLiveData<T>, action: (t: T) -> Unit) {
        data.observe(this, action)
    }
}